<script lang="ts" setup name="XtxNumbox">
import { getCurrentInstance, ComponentInternalInstance } from "vue"
let { proxy } = getCurrentInstance() as ComponentInternalInstance
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1
  },
  min: {
    type: Number,
    default: 1
  },
  max: {
    type: Number,
    default: 1
  },
  label: {
    type: String,
    default: ''
  }
})
const emit = defineEmits<{
  (e: 'update:modelValue', value: number): void
  (e: 'change', value: number): void
}>()
// 减
const sub = () => {
  if (props.modelValue <= props.min) return
  emit('update:modelValue', props.modelValue - 1)
  // emit('change', props.modelValue - 1)
}
// 加
const add = () => {
  if (props.modelValue >= props.max) return
  emit('update:modelValue', props.modelValue + 1)
  // emit('change', props.modelValue + 1)
}
// 手动输入
const handleChange = (e: Event) => {
  const element = e.target as HTMLInputElement // 输入框
  let val = +element.value
  // 非数字判定  isNaN(is Not a Number 是,不是一个数字) isNaN(20) false 
  // isNaN 检测非数字是true 检测数字是false
  if (isNaN(val)) val = props.min
  // 最大值判定
  if (val >= props.max) val = props.max
  // 最小值判定
  if (val <= props.min) val = props.min
  emit('update:modelValue', val)
  // emit('change', val)
  // 第一次输入字母, 失焦后会变成1 再写新的字母 就不会变了
  //  abc ==> 1  xyz ==> 1
  // 强制dom更新 
  proxy!.$forceUpdate()
}

// 点击了修改数量 可以将最新的值 传递给父组件
const changeCount = () => {
  emit('change', props.modelValue)
}
</script>
<template>
  <div class="xtx-numbox" @click="changeCount">
    <div class="label" v-if="label">{{ label }}</div>
    <div class="numbox">
      <a href="javascript:;" @click="sub" :class="{ 'not-allowed': modelValue <= min }">-</a>
      <input type="text" :value="modelValue" @change="handleChange" />
      <a href="javascript:;" @click="add" :class="{ 'not-allowed': modelValue >= max }">+</a>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;

  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }

  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;

    >a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;

      &.not-allowed {
        cursor: not-allowed;
      }

      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }

      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }

    >input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>